/**
 * @description controller channel
 */

const { createChannel, deleteChannel, updateChannel, findChannels } = require('../../service/channels')
const { findOneWork } = require('../../service/works')
const {
  createChannelFailInfo,
  createChannelDbErrorFailInfo,
  updateChannelFailInfo,
  updateChannelDbErrorFailInfo,
  findChannelListFailInfo
} = require('../../res-model/failInfo/index')
const { ErrorRes, SuccessRes } = require('../../res-model/index')

const { nanoid } = require('nanoid')

/**
 * 创建渠道
 * @param {string} author 作者 username（保证安全性，避免查询他人作品）
 * @param {object} data 渠道数据
 */
async function createChannels(username, data = {}) {
  const { workId, name } = data
  if (!workId || !name) return new ErrorRes(createChannelFailInfo, '标题或作品 id 不能为空')

  const work = await findOneWork({ id: workId, author: username })

  if (!work) {
    return new ErrorRes(createChannelFailInfo, 'id 或 author 不匹配')
  }

  const newChannel = {
    name,
    id: nanoid(6),
    status: 1 //状态：0-删除，1-正常
  }

  try {
    // $push 插入数组
    const result = await createChannel(workId, { $push: { channels: newChannel } })
    if (result == null) {
      return new ErrorRes(createChannelFailInfo)
    }
    return new SuccessRes(newChannel)
  } catch (ex) {
    console.error('创建渠道错误', ex)
    return new ErrorRes(createChannelDbErrorFailInfo)
  }
}

/**
 * 删除渠道
 * @param {string} id // channel ID
 */
async function deleteChannels(id) {
  if (!id) return new ErrorRes(updateChannelFailInfo, 'id 不能为空')

  try {
    const result = await updateChannel(id, { $set: { 'channels.$.status': 0 } }) // 假删除，实际更新 status
    if (result) {
      return new SuccessRes()
    }
    return new ErrorRes(updateChannelFailInfo)
  } catch (ex) {
    console.error('删除渠道错误', ex)
    return new ErrorRes(updateChannelDbErrorFailInfo)
  }
}

/**
 * 更新渠道
 * @param {string} id channel ID
 * @param {string} name 名称
 */
async function updateChannelName(id, name) {
  if (!id || !name) return new ErrorRes(updateChannelFailInfo, 'id 和名称不能为空')

  try {
    // $set 修改数组  channels.$ 代表查询到的下标 也可要指定下标 如 channels.0
    const result = await updateChannel(id, { $set: { 'channels.$.name': name } })
    if (result) {
      return new SuccessRes()
    }
    return new ErrorRes(updateChannelFailInfo)
  } catch (ex) {
    console.error('更新渠道错误', ex)
    return new ErrorRes(updateChannelDbErrorFailInfo)
  }
}

/**
 * 获取作品的渠道列表
 * @param {string} workId 作品 id
 */
async function getWorkChannels(workId) {
  if (!workId) return new ErrorRes(findChannelListFailInfo, 'id 或名称不能为空')

  const result = await findChannels({ id: workId })
  if (result) {
    return new SuccessRes(result)
  }
  return new ErrorRes(findChannelListFailInfo)
}

module.exports = {
  createChannels,
  deleteChannels,
  updateChannelName,
  getWorkChannels
}
